package com.wh.wisdomsite.xbox.utils.server;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpStatus;
import org.apache.http.protocol.HTTP;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 采用HttpURLConnection 和  URLConnection连接服务器进行数据通讯
 * @Package com.wh.wisdomsite.xbox.utils.server
 * @author 谢泽鹏
 * @date 2014年10月14日 下午2:10:42
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 * @version V1.0
 */
public class connToserver_URL {

    private static final Log logger = LogFactory.getLog(connToserver_URL.class);


    /**
	 * 发送GET请求信息
	 * @param url  请求url地址
	 * @param map  请求参数map
	 * @return String   响应结果数据
	 */
	public static String sendGetRequest(String url, Map<String, String> map) {
		//声明result响应结果
		StringBuilder result = null;
		//声明URLConnection对象
		URLConnection urlConnection = null;
		//声明BufferedReader对象
		BufferedReader bufferedReader = null;
		try {
			StringBuilder sb = new StringBuilder();
			result = new StringBuilder();
			if (null != map && !map.isEmpty()) {
				for (Map.Entry<String, String> entry : map.entrySet()) {
					sb.append(entry.getKey()).append("=");
					sb.append(URLEncoder.encode(entry.getValue(), HTTP.UTF_8));
					sb.append("&");
				}
				sb.deleteCharAt(sb.length() - 1);
			}
			//获取请求参数
			String params = sb.toString();
			//获取请求地址
			String urlName = url + "?" + params;
            logger.info("sendGetRequest->>请求参数信息：" + params);
            logger.info("sendGetRequest->>请求URL地址：" + urlName);
			//创建实际URL对象
			URL realUrl = new URL(urlName);
			//打开和URL之间的连接
			urlConnection = realUrl.openConnection();
			//设置通用的请求属性
			//设置请求拦截
			urlConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
			//设置请求语言
			urlConnection.setRequestProperty("Accept-Language", "zh-CN");
			//设置请求协议
			urlConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
			//设置请求类型
			urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			//设置保持连接
			urlConnection.setRequestProperty("Connection", "Keep-Alive");
			//建立实际的连接
			urlConnection.connect();
			//获取所有响应头字段
			Map<String, List<String>> mapHeader = urlConnection.getHeaderFields();
			//遍历所有的响应头字段
			for (String key : mapHeader.keySet()) {
                logger.info("sendGetRequest->>key: "  +  mapHeader.get(key) + "");
			}
			//读出数据信息
			bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
            logger.error("sendGetRequest->>发送GET请求出现异常！" + e.getMessage());
			return null;
		} finally {
			try {
				if (null != bufferedReader) {
					bufferedReader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
                logger.error("sendGetRequest->>发送GET请求,资源管理出现异常！" + e.getMessage());
				return null;
			}
		}
				return result.toString();
	}

	

	/**
	 * 发送POST请求信息
	 * @param url  请求url地址
	 * @param map  请求参数map
	 * @return String   响应结果数据
	 */
	public static String sendPostRequest(String url, Map<String, String> map) {
		//声明result响应结果
		StringBuilder result = null;
		//声明HttpURLConnection对象
		HttpURLConnection httpURLConnection = null;
		//声明OutputStream输出流
		OutputStream outStream = null;
		//声明ByteArrayOutputStream输出流
		ByteArrayOutputStream byteoutSteam = null;
		//声明InputStream输入流
		InputStream inStream = null;
		try {
			StringBuilder sb = new StringBuilder();
			result = new StringBuilder();
			if (null != map && !map.isEmpty()) {
				for (Map.Entry<String, String> entry : map.entrySet()) {
					sb.append(entry.getKey()).append("=");
					sb.append(URLEncoder.encode(entry.getValue(), HTTP.UTF_8));
					sb.append("&");
				}
				sb.deleteCharAt(sb.length() - 1);
			}
			//获取请求参数
			String params = sb.toString();
			byte[] paramsdata = params.getBytes();
            logger.info("sendPostRequest->>请求参数信息：" + params);
            logger.info("sendPostRequest->>请求URL地址：" + url);
			//创建URL对象
			URL urlName = new URL(url);
			//打开HttpURLConnection连接对象
			httpURLConnection = (HttpURLConnection) urlName.openConnection();
			//允许对外发送请求参数
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			//获取请求头头文件信息
			Map<String, List<String>> mapHeader = httpURLConnection.getHeaderFields();
			//遍历所有的响应头字段
			for (String key : mapHeader.keySet()) {
                logger.info("sendPostRequest->>"+ key + mapHeader.get(key) + "");
			}
			//不进行缓存
			httpURLConnection.setUseCaches(false);
			//设置连接超时30s
			httpURLConnection.setConnectTimeout(connToserver_Setting.CONNECTION_TIMEOUT);
			//设置读取超时时间60s
			httpURLConnection.setReadTimeout(connToserver_Setting.READ_TIMEOUT);
			//设置请求方式
			httpURLConnection.setRequestMethod("POST");
			//设置conn通用属性
			//设置请求拦截
			httpURLConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
			//设置请求语言
			httpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
			//设置请求协议
			httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
			//设置请求类型
			httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			httpURLConnection.setRequestProperty("Content-Length", String.valueOf(paramsdata.length));
			//设置保持连接
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			//获取OutputStream输出流
			outStream = httpURLConnection.getOutputStream();
			//把参数发送出去
			outStream.write(paramsdata);
			//刷新
			outStream.flush();
			//判断请求响应状态成功
			if (httpURLConnection.getResponseCode() == HttpStatus.SC_OK) {
				//创建ByteArrayOutputStream对象
				byteoutSteam = new ByteArrayOutputStream();
				//获取输入流
				inStream = httpURLConnection.getInputStream();
				byte[] buffer = new byte[connToserver_Setting.BUFFERSIZE];
				int len = -1;
				while ((len = inStream.read(buffer)) != -1) {
					byteoutSteam.write(buffer, 0, len);
				}
				result.append(new String(byteoutSteam.toByteArray()));
			}
		} catch (Exception e) {
			e.printStackTrace();
            logger.error("sendPostRequest->>发送POST请求出现异常！" + e.getMessage());
			return null;
		} finally{
			try {
				if(null != byteoutSteam){
					byteoutSteam.close();
				}
				if(null != outStream){
					outStream.close();
				}
				if(null != inStream){
					inStream.close();
				}
				if(null != httpURLConnection){
					httpURLConnection.disconnect();
				}
			} catch (IOException e) {
				e.printStackTrace();
                logger.error("sendPostRequest->>发送POST请求,资源管理出现异常！" + e.getMessage());
				return null;
			}
		}
			return result.toString();
	}
	
	
}
